<?php

namespace app\admin\controller\financing;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use think\Env;

/**
 * 储值卡充值记录
 *
 * @icon fa fa-user
 */
class Card extends Backend
{


    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $models = null;
    protected $categorylist = [];
    private $redis;

    public function _initialize()
    {
        parent::_initialize();
        //$this->model = new \app\admin\model\Registration;
        $this->model = new \app\admin\model\Cards;
        $this->redis = redis(Env::get('redis.host'), Env::get('redis.port'), Env::get('redis.pwd'), Env::get('redis.db'));
    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                //->with(["users"=>['id','name'],"medic"=>['id','name'],"info"=>['id','name']])
                //->with(["users"=>['id','nickname','phone']])
                ->with([
                    'users' => function ($query) {
                        $query->withField('id,nickname,phone');
                    }
                ])
                ->where($where)
                ->where('cards.type',1)
                ->order('id', 'desc')
                ->paginate($limit);

            //1代表转账，2代表现金，3代表pos机，4代表支付宝，5代表微信
            if (!empty($list->items())){
                foreach ($list->items() as $k=>$v){
                    switch ($v->pay){
                        case 1:
                            $list->items()[$k]['pay'] = '转账';
                            break;
                        case 2:
                            $list->items()[$k]['pay'] = '现金';
                            break;
                        case 3:
                            $list->items()[$k]['pay'] = 'pos机';
                            break;
                        case 4:
                            $list->items()[$k]['pay'] = '支付宝';
                            break;
                        case 5:
                            $list->items()[$k]['pay'] = '微信';
                            break;
                        case 6:
                            $list->items()[$k]['pay'] = '兑换';
                            break;
                        default:
                            $list->items()[$k]['pay'] = '';
                            break;
                    }
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 查询操作
     *
     */
    public function for(){
        $arr = request()->param();

        $data = Db::table('fa_users')
            ->where('id',$arr['id'])
            ->find();

        if (empty($data)){
            $this->error('用户数据为空');
        }else{

            if ($data['pid'] != 0){
                $this->error('该账户不是主账户');
            }

            $this->success('成功','',$data['nickname']);
        }

    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                if (empty($params['user_id'])){
                    $this->error(__('客户id不能为空'));
                }

                if (empty($params['money'])){
                    $this->error(__('金额不能为空或0'));
                }

                if (!is_numeric($params['money'])){
                    $this->error(__('金额只能为数字类型'));
                }

                $user_arr = Db::table('fa_users')
                    ->where('id',$params['user_id'])
                    ->find();

                if ($user_arr['pid'] != 0){
                    $this->error('该账户不是主账户');
                }


                $params['admin_id'] = $this->auth->id;
                $params['admin_name'] = $this->auth->nickname;
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }


                    $updates = Db::table('fa_users')
                        ->where('id',$params['user_id'])
                        ->setInc('money',$params['money']);

                    $params['type'] = 1;
                    $result = $this->model->allowField(true)->save($params);

                    if (($updates !== false) && ($result !== false)){
                        Db::commit();
                    }else{
                        Db::rollback();
                        $this->error('失败');
                    }

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }




}
